# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2018/12/14
# python-version    : Python 3.7.0
# description       : 登陆窗口

import wx
import telnetlib
import _thread as thread
from time import sleep
from com.python.demo.mutil_chatting_room.entities.ChatFrame import ChatFrame

global conn

class LoginFrame(wx.Frame):
    "登录窗口"

    def __init__(self,conn, parent, id, title, size):
        "界面初始化，添加控件，并绑定事件"
        wx.Frame.__init__(self, parent, id, title)
        self.conn = conn
        self.SetSize(size)
        self.Center()
        self.serverAddressLabel = wx.StaticText(self, label="服务地址", pos=(10, 50), size=(120, 50))
        self.userNameLabel = wx.StaticText(self, label="用户名", pos=(40, 100), size=(120, 25))
        self.serverAddress = wx.TextCtrl(self,pos=(120, 47), size=(150, 25))
        self.serverAddress.write('127.0.0.1:6666')
        self.userName = wx.TextCtrl(self, pos=(120, 97), size=(150, 25))
        self.loginButton = wx.Button(self, label="登录", pos=(80, 145), size=(130, 30))
        # 绑定登录事件
        self.loginButton.Bind(wx.EVT_BUTTON, self.login)
        self.Show()

    def login(self, event):
        "登录处理"
        try:
            serverAddress = self.serverAddress.GetLineText(0).split(':')
            self.conn.open(serverAddress[0], port=int(serverAddress[1]), timeout=10)
            response = self.conn.read_some()
            if response != b'Connect Successful':
                self.showDialog("错误", "连接失败！", (200, 100))
                return
            self.conn.write(("登录" + str(self.userName.GetLineText(0)) + '\n').encode('utf-8'))
            response = self.conn.read_some()
            if response == b"Username is empty!":
                self.showDialog("错误", "用户名为空！", (200, 100))
            elif response == b"Username is exists":
                self.showDialog("错误", "用户名已存在！", (200, 100))
            else:
                self.close()
                ChatFrame(self.conn,None, 2, title="多人聊天室", size=(500, 400))
        except Exception as e:
            self.showDialog("异常", "连接失败", (200, 100))

    def showDialog(self, title, content, size):
        "显示错误信息对话框"
        dialog = wx.Dialog(self, title=title, size=size)
        dialog.Center()
        wx.StaticText(dialog, label=content,pos=(40,100))
        dialog.ShowModal()

    def __delete__(self, instance):
        self.Close()
